<template>
	<view class="edit-container">
		<uv-toast ref="toast"></uv-toast>
		<!-- 顶部图片上传区域 -->
		<view class="upload-section" @click.stop="uploadImage">
			<image class="store-image" :src="formData.image || defaultImage" mode="aspectFill" />
			<view class="upload-mask">
				<uv-icon name="camera-fill" size="40" color="#fff"></uv-icon>
				<text>{{ formData.image ? '更换店铺图片' : '上传店铺图片' }}</text>
			</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-container">
			<!-- 基本信息 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="info-circle-fill" size="32" color="#3c9cff"></uv-icon>
					<text>基本信息</text>
				</view>

				<view class="input-group">
					<text class="label required">门店名称</text>
					<uv-input v-model="formData.name" placeholder="请输入门店名称" maxlength="50" :border="false" />
				</view>

				<view class="input-group">
					<text class="label required">商家名称</text>
					<uv-input v-model="formData.merchantName" placeholder="请输入商家名称" maxlength="50" :border="false" />
				</view>

				<view class="input-group">
					<text class="label required">负责人</text>
					<text class="director">{{ merchant.director }}</text>
				</view>

				<view class="input-group">
					<text class="label required">营业时间</text>
					<uv-input v-model="formData.openingHours" placeholder="例如: 09:00-18:00" maxlength="30"
						:border="false" />
				</view>
			</view>

			<!-- 联系方式 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="phone" size="32" color="#3c9cff"></uv-icon>
					<text>联系方式</text>
				</view>

				<view class="input-group">
					<text class="label required">联系电话</text>
					<uv-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="11" type="number"
						:border="false" />
				</view>
			</view>

			<!-- 店铺地址 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="map" size="32" color="#3c9cff"></uv-icon>
					<text>店铺地址</text>
				</view>

				<view class="location-picker">
					<view class="address-picker">
						<view class="location-btn" @tap="chooseLocation">
							<view class="btn-content">
								<view class="left">
									<uv-icon name="map-fill" size="40" color="#3c9cff"></uv-icon>
									<text class="btn-text">{{ formData.street || '点击选择店铺位置' }}</text>
								</view>
								<uv-icon name="arrow-right" size="24" color="#909399"></uv-icon>
							</view>
						</view>

						<!-- 地址预览 -->
						<view class="address-preview" v-if="formData.street">
							<view class="preview-item">
								<text class="label">详细地址</text>
								<text class="value">{{ formData.street }}</text>
							</view>
							<view class="preview-item">
								<text class="label">所在地区</text>
								<text class="value">{{ formData.district }}</text>
							</view>
						</view>

						<!-- 地图预览 -->
						<map v-if="formData.latitude && formData.longitude" :latitude="Number(formData.latitude)"
							:longitude="Number(formData.longitude)" :markers="markes" class="map-preview">
						</map>
					</view>
				</view>
			</view>

			<!-- 店铺简介 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="file-text" size="32" color="#3c9cff"></uv-icon>
					<text>店铺简介</text>
				</view>

				<view class="textarea-group">
					<uv-textarea v-model="formData.des" placeholder="请输入店铺简介" maxlength="1000" height="200"
						count></uv-textarea>
				</view>
			</view>
		</view>

		<!-- 底部保存按钮 -->
		<view class="bottom-button">
			<!-- 重置按钮 -->
			<view class="custom-button outline" @tap="resetForm">
				<text>重置表单</text>
			</view>
			
			<!-- 保存按钮 -->
			<view class="custom-button primary" :class="{ disabled: saving }" @tap="saveInfo">
				<text v-if="!saving">保存修改</text>
				<view v-else class="loading-icon">
					<uv-loading-icon size="30" mode="circle" color="#ffffff"></uv-loading-icon>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				defaultImage: '/static/lyf.jpg',
				saving: false,
				formData: {
					name: '',
					merchantName: '',
					phone: '',
					street: '',
					latitude: '',
					longitude: '',
					des: '',
					image: ''
				},
				markers: [{
					id: 1,
					latitude: 0,
					longitude: 0,
					iconPath: '/static/location.png', // 需要添加标记图标
					width: 32,
					height: 32
				}],
				merchant: {},
				originalImage: '', // 保存初始图片路径
				hasUnsavedChanges: false, // 是否有未保存的更改
			}
		},

		methods: {
			showToast(msg, type, duration) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			async fetchDelImage() {
				try{
					const data = await this.$http.post('/auth/image/del');
				}catch(e){
					console.error('删除照片失败', e);
				}
			},
			async uploadImage() {
				try {
					const res = await this.$http.urlImgUpload('/auth/merchant/image/upload', {
						name: 'file',
						maxSize: 1024 * 1024 * 5,
						count: 1
					});

					// 返回图片路径
					if (res) {
						this.formData.image = res[0];
						this.hasUnsavedChanges = true; // 标记有未保存的更改
						this.showToast('上传成功', 'success', 1000);
					}

				} catch (e) {
					this.showToast('上传失败', 'error', 1000);
				}
			},
			async getMerchantInfo() {
				try {
					const data = await this.$http.post('/auth/merchant/info');
					if (data) {
						this.merchant = data;
						this.formData = this.merchant;
						this.originalImage = this.merchant.image; // 保存初始图片路径
					} else {
						uni.navigateBack();
						this.showToast('获取店铺信息失败', 'default', 1000);
					}
				} catch (e) {
					console.error(e);
					this.showToast(e.msg, 'default', 1000);
					uni.navigateBack();
				}
			},
			async chooseLocation() {
				try {
					const location = await uni.chooseLocation()

					this.formData.street = location.address
					this.formData.latitude = location.latitude
					this.formData.longitude = location.longitude

					// 更新地图标记
					this.markers[0].latitude = location.latitude
					this.markers[0].longitude = location.longitude

				} catch (error) {
					console.err(error);
					this.showToast('选择位置失败', 'default', 1000);
				}
			},

			async saveInfo() {
				if (this.saving) return

				try {
					this.saving = true
					// 表单验证
					if (!this.validateForm()) {
						return
					}

					// 保存逻辑
					await this.$http.post('/auth/merchant/info/update', this.formData)

					// 保存成功后更新初始图片路径
					this.originalImage = this.formData.image;
					this.hasUnsavedChanges = false;

					this.showToast('保存成功', 'success', 1000);

					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} catch (error) {
					this.showToast('保存失败', 'error', 1000);
				} finally {
					this.saving = false
				}
			},

			// 添加表单验证方法
			validateForm() {
				if (!this.formData.name) {
					this.showToast('请输入门店名称', 'default', 1000);
					return false
				}
				if (!this.formData.merchantName) {
					this.showToast('请输入商家名称', 'default', 1000);
					return false
				}
				if (!this.formData.phone) {
					this.showToast('请输入联系电话', 'default', 1000);
					return false
				}
				// 手机号格式验证
				if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
					this.showToast('请输入正确的手机号', 'default', 1000);
					return false
				}
				return true
			},

			// 重置表单
			resetForm() {
				uni.showModal({
					title: '提示',
					content: '确定要重置表单吗？',
					success: (res) => {
						if (res.confirm) {
							// 重新赋值
							this.formData = JSON.parse(JSON.stringify(this.merchant));
							this.showToast('已重置', 'success', 1000);
						}
					}
				});
			},

			// 检查是否需要删除未保存的图片
			async checkUnsavedImage() {
				if (this.hasUnsavedChanges && this.formData.image !== this.originalImage) {
					try {
						await this.fetchDelImage();
						console.log('已删除未保存的图片');
					} catch (error) {
						console.error('删除未保存的图片失败', error);
					}
				}
			},

			// 退出前确认
			async handlePageExit() {
				if (this.hasUnsavedChanges) {
					uni.showModal({
						title: '提示',
						content: '您有未保存的更改，确定要退出吗？',
						success: async (res) => {
							if (res.confirm) {
								await this.checkUnsavedImage();
								uni.navigateBack();
							}
						}
					});
					return true;
				}
				return false;
			}
		},

		onLoad() {
			// 获取当前商家信息
			this.getMerchantInfo()
		},

		// 监听页面返回
		onBackPress() {
			if (this.hasUnsavedChanges) {
				this.handlePageExit();
				return true; // 阻止默认返回行为
			}
			return false;
		},

		// 监听页面卸载
		onUnload() {
			// 如果有未保存的更改，删除上传的图片
			this.checkUnsavedImage();
		}
	}
</script>

<style lang="scss" scoped>
	@import 'edit_merchant_info.scss';
</style>